package sc.hibernate.config;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

/**
 * Hibernate session factory for DAO. Allow to map Java object with MySQL connexion.
 * To configure the connexion see hibernate.cfg.xml
 * 
 * @author Cédric Rais
 *
 */
public class HibernateSession {
	private static SessionFactory sessionFactory; 
	private ServiceRegistry serviceRegistry;
	
	private HibernateSession(){
		try{
			// This step will read hibernate.cfg.xml and prepare hibernate for use
			Configuration configuration = new Configuration(); 
		    configuration.configure(); 
		    serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();         
		    sessionFactory = configuration.buildSessionFactory(serviceRegistry); 
		}catch(Exception e){
			System.out.println(e.getMessage());
		}
	}
		
	public static void executeSQL(String sql){
		getSessionFactory();
		try{
			Session session = sessionFactory.openSession();
			session.beginTransaction();	
			session.createSQLQuery(sql).executeUpdate();
			session.getTransaction().commit();
	   		session.flush();
			session.close();
		}catch(org.hibernate.exception.ConstraintViolationException e){
			System.err.println("Double sector primary key");
		}catch(HibernateException e){
			e.printStackTrace();
		}
	}
	
	/**
	 * Get the single Hibernate session
	 * 
	 * @return session
	 */
	public static SessionFactory getSessionFactory() {
		if (sessionFactory == null)
			new HibernateSession(); // instanciation retardée
		return sessionFactory;
	}
}
